package edu.upc.clase.demo.dao.impl;

import edu.upc.clase.demo.dao.InstrumentoDao;
import edu.upc.clase.demo.entity.Instrumento;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

/**
 *
 * @author cmunoz
 */
@Repository
public class InstrumentoDaoImpl  extends SimpleJdbcDaoSupport implements InstrumentoDao{
    
    private static Logger log = LoggerFactory.getLogger(InstrumentoDaoImpl.class);

    @Autowired
    public InstrumentoDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }
  
     @Override
    public Integer registrarInstrumento(Instrumento instrumento) {

        getJdbcTemplate().update(
                "insert into instrumento(idinstrumento, marca, modelo, fechafabri, tipo, caracteristica, costoporhora) VALUES(?, ?, ?, ?, ?, ?, ?)",
                instrumento.getidInstrumento(),instrumento.getMarca(),instrumento.getModelo(),instrumento.getFechFabri(), instrumento.getTipo(), instrumento.getCaracteristica(),instrumento.getcostoporhora());
                return getSimpleJdbcTemplate().queryForInt("select last_insert_id()");
    }  
     
    @Override
    public void actualizarInstrumento(Instrumento instrumento) {

        getJdbcTemplate().update(
                "update into instrumento(idinstrumento, marca, modelo, fechafabri, tipo, caracteristica, costoporhora) VALUES(?, ?, ?, ?, ?, ?, ?)",
                instrumento.getidInstrumento(),instrumento.getMarca(),instrumento.getModelo(),instrumento.getFechFabri(), instrumento.getTipo(), instrumento.getCaracteristica(),instrumento.getcostoporhora());
    }      
    @Override
    public Instrumento buscar(Integer idInstrumento) {
        try {
            return getSimpleJdbcTemplate().queryForObject(
                    "select caracteristica, costoporhora from instrumento where idInstrumento=?",
                    new BeanPropertyRowMapper<Instrumento>(Instrumento.class), idInstrumento);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    } 
     
}
